<?php
namespace frontend\modules\Api\controllers;

use common\services\TallyStockBalanceService;
use Yii;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;
use yii\base\DynamicModel;

/**
 * Class StockBalanceController
 *
 * @package frontend\modules\Api\controllers
 * @desc 库存余额管理
 */
class StockBalanceController extends ApiController
{
    /**
     * @return array
     * 引入行为验证 过滤授权
     */
    public function behaviors()
    {
        $config = [
            'access' => [
                'class' => AccessControl::className(),
                'denyCallback' => function($rule, $action){
                    return self::failureResponse(100001, '请先登录!',[]);
                },
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ]
                ]
            ],
        ];
        return ArrayHelper::merge(parent::behaviors(), $config);
    }

    /**
     * 库存余额 仓库维度统计
     * @throws
     */
    public function actionHouse()
    {
        $condition = Yii::$app->request->get();
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId,'read');
        $list = TallyStockBalanceService::summaryHouse($tallyId,$condition);
        return self::successResponse($list);
    }

    /**
     * 产品维度的库存余额统计
     * @throws
     */
    public function actionProduct()
    {
        $condition = Yii::$app->request->get();
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId,'read');
        $list = TallyStockBalanceService::summaryProduct($tallyId,$condition);
        return self::successResponse($list);
    }

    /**
     * 某个仓库下的库存统计 分产品
     * @throws
     */
    public function actionHouseDetail()
    {
        $condition = Yii::$app->request->get();
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $houseId = Yii::$app->getRequest()->get('house_id');
        if(!$houseId){
            return self::failureResponse(500,'仓库ID不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId,'read');

        $list = TallyStockBalanceService::houseDetail($tallyId,$houseId,$condition);
        if($list) {
            return self::successResponse($list);
        }else{
            return self::failureResponse(500,TallyStockBalanceService::getError());
        }
    }

    /**
     * 某个产品下的库存统计 分仓库
     * @throws
     */
    public function actionProductDetail()
    {
        $condition = Yii::$app->request->get();
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $productId = Yii::$app->getRequest()->get('product_id');
        if(!$productId){
            return self::failureResponse(500,'产品ID不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId,'read');

        $list = TallyStockBalanceService::productDetail($tallyId,$productId,$condition);
        if($list) {
            return self::successResponse($list);
        }else{
            return self::failureResponse(500,TallyStockBalanceService::getError());
        }
    }

    /**
     * 新增产品入库
     * @throws
     */
    public function actionInHouse()
    {
        $tallyId = Yii::$app->getRequest()->post('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId,'read');

        $form = DynamicModel::validateData([
            'tally_id' => Yii::$app->getRequest()->post('tally_id'),
            'house_id' => Yii::$app->getRequest()->post('house_id'),
            'product_detail' => Yii::$app->getRequest()->post('product_detail',[]),
            'project_id' => Yii::$app->getRequest()->post('project_id',0),
            'memo' => Yii::$app->getRequest()->post('memo',''),
        ],[
            [['house_id','tally_id'], 'required'],
            ['memo', 'filter', 'filter' => 'trim'],
        ]);
        if ($form->hasErrors()) {
            return self::failureResponse(500,current($form->getFirstErrors()));
        }

        $res = TallyStockBalanceService::operateHouse($tallyId,'in',ArrayHelper::toArray($form));

        // 触发写日志 TODO...

        if($res) {
            return self::successResponse();
        }else {
            return self::failureResponse(500,TallyStockBalanceService::getError());
        }
    }

    /**
     * 产品出库
     * @throws
     */
    public function actionOutHouse()
    {
        $tallyId = Yii::$app->getRequest()->post('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId,'read');

        $form = DynamicModel::validateData([
            'tally_id' => Yii::$app->getRequest()->post('tally_id'),
            'house_id' => Yii::$app->getRequest()->post('house_id'),
            'product_detail' => Yii::$app->getRequest()->post('product_detail',[]),
            'project_id' => Yii::$app->getRequest()->post('project_id',0),
            'memo' => Yii::$app->getRequest()->post('memo',''),
        ],[
            [['house_id','tally_id'], 'required'],
            ['memo', 'filter', 'filter' => 'trim'],
        ]);
        if ($form->hasErrors()) {
            return self::failureResponse(500,current($form->getFirstErrors()));
        }

        $res = TallyStockBalanceService::operateHouse($tallyId,'out',ArrayHelper::toArray($form));

        // 触发写日志 TODO...

        if($res) {
            return self::successResponse();
        }else {
            return self::failureResponse(500,TallyStockBalanceService::getError());
        }
    }

    /**
     * 调拨库存
     * @throws \yii\base\ExitException
     * @throws \yii\base\InvalidConfigException
     */
    public function actionTransferHouse()
    {
        $tallyId = Yii::$app->getRequest()->post('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId,'read');

        $form = DynamicModel::validateData([
            'tally_id' => Yii::$app->getRequest()->post('tally_id'),
            'house_id' => Yii::$app->getRequest()->post('house_id'),
            'house_id_from' => Yii::$app->getRequest()->post('house_id_from'),
            'product_detail' => Yii::$app->getRequest()->post('product_detail',[]),
            'project_id' => Yii::$app->getRequest()->post('project_id',0),
            'memo' => Yii::$app->getRequest()->post('memo',''),
        ],[
            [['house_id','house_id_from','tally_id'], 'required'],
            ['memo', 'filter', 'filter' => 'trim'],
        ]);
        if ($form->hasErrors()) {
            return self::failureResponse(500,current($form->getFirstErrors()));
        }

        $res = TallyStockBalanceService::operateHouse($tallyId,'trans',ArrayHelper::toArray($form));

        // 触发写日志 TODO...

        if($res) {
            return self::successResponse();
        }else {
            return self::failureResponse(500,TallyStockBalanceService::getError());
        }
    }

    /**
     * 库存流水记录 带分页
     * @throws \yii\base\ExitException
     */
    public function actionFlow()
    {
        $condition = Yii::$app->request->get();
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId,'read');
        $list = TallyStockBalanceService::flowList($tallyId,$condition);
        return self::successResponse($list);
    }


    /**
     * 库存流水记录 带分页
     * @throws \yii\base\ExitException
     */
    public function actionFlowWithNotPage()
    {
        $condition = Yii::$app->request->get();
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $list = TallyStockBalanceService::flowListWithPage($tallyId,$condition);
        return self::successResponse($list);
    }

    /**
     * 获取统计数据 包含全部余额等数据
     * @throws \yii\base\ExitException
     */
    public function actionSummary()
    {
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId,'read');
        $list = TallyStockBalanceService::getSummary($tallyId);
        return self::successResponse($list);
    }



    public function actionDelflow(){
        $condition = Yii::$app->request->post();
        $tallyId = Yii::$app->getRequest()->post('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $list = TallyStockBalanceService::delFlow($tallyId,$condition);
    }
}
